package priv.lhy.securitydemo.entity;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import priv.lhy.securitydemo.entity.Users;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author: lihy
 * date: 2019/10/5 11:24
 * description:
 */
public class AuthorityUser implements UserDetails {

    private Users user;

    public AuthorityUser(Users user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Optional.ofNullable(user.getAuthorities()).orElse(Collections.emptyList())
                .stream().map(this::convertAuthority).collect(Collectors.toList());
    }

    private GrantedAuthority convertAuthority(Authorities authority) {
        return new SimpleGrantedAuthority(authority.getAuthority());
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getEnable() == 0;
    }
}
